package com.mgface.zookeeper;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;

public class getChildren {
	private static ZooKeeper zk = null;
	public static void change(WatchedEvent event){
		try {
			log.info("变更后的数据:"+zk.getChildren(event.getPath(),true));
		} catch (KeeperException | InterruptedException e) {
			e.printStackTrace();
		}
	}
	private static Logger log= Logger.getLogger(getChildren.class);
	public static void main(String[] args) throws Exception {
		CountDownLatch cdl = new CountDownLatch(1);
		zk = new ZooKeeper("192.168.244.130:2182", 2_000, e->{
			log.info("接收到的event:"+e);
			if(e.getState()==KeeperState.SyncConnected){
				if(e.getType()==EventType.None&&e.getPath()==null){
					cdl.countDown();
				}else if(e.getType()==EventType.NodeChildrenChanged){
						change(e);
				}
			}
		});
		log.info("ZK状态:"+zk.getState().toString());
		Instant start = Instant.now();
		cdl.await();
		Instant end = Instant.now();
		Duration duration = Duration.between(start, end);
		log.info("花费时间:"+duration.toMillis()+"ms");
		log.info("zookeeper session established");
		//List<String> list = zk.getChildren("/zk", true);
		//log.info("list:"+list);
		CountDownLatch cdl2 = new CountDownLatch(1);
//		List<String> list = zk.getChildren("/zk", e->{
//			log.info(e.getType());
//			cdl2.countDown();
//		});
//		log.info("list:"+list);
//		cdl2.await();
		//Stat stat = new Stat();
		//List<String> list = zk.getChildren("/zk", true, stat);
		//log.info("list:"+list+",stat:"+stat);
		zk.getChildren("/zk",true, (i,s,obj,list)->{
			log.info("[i="+i+",s="+s+",obj="+obj+",list="+list+"]");
			cdl2.countDown();
		}, "this is  context");
		cdl2.await();
		Thread.sleep(10_000);
	}

}
